package cn.com.oyat.idea.controller.virtual;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.com.oyat.idea.service.SsdpDiscoveryService;

import java.net.*;
import java.util.Enumeration;

@RestController
public class DiagnosticController {

    @Autowired
    private SsdpDiscoveryService ssdpService;

    @Value("${server.port:8191}")
    private int serverPort;

    /**
     * 诊断报告
     */
    @GetMapping("/diagnose")
    public String diagnose() {
        StringBuilder result = new StringBuilder();
        result.append("=== DLNA设备诊断报告 ===\n\n");

        // 1. 检查网络接口
        result.append("1. 网络接口检查:\n");
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isUp() && !iface.isLoopback()) {
                    result.append("   ✅ ").append(iface.getDisplayName()).append("\n");
                    Enumeration<InetAddress> addresses = iface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address) {
                            result.append("      IP: ").append(addr.getHostAddress()).append("\n");
                        }
                    }
                }
            }
        } catch (Exception e) {
            result.append("   ❌ 网络接口检查失败: ").append(e.getMessage()).append("\n");
        }

        // 2. 检查SSDP服务状态
        result.append("\n2. SSDP服务状态:\n");
        String localIp = ssdpService.getLocalIp();
        if (localIp != null) {
            result.append("   ✅ 服务IP: ").append(localIp).append("\n");
            result.append("   ✅ 服务端口: ").append(serverPort).append("\n");
        } else {
            result.append("   ❌ 服务未获取到IP地址\n");
        }

        // 3. 测试组播通信
        result.append("\n3. 组播通信测试:\n");
        testMulticastCommunication(result);

        // 4. 测试设备描述文档
        result.append("\n4. 设备描述文档测试:\n");
        try {
            URL deviceUrl = new URL("http://" + (localIp != null ? localIp : "127.0.0.1") + ":" + serverPort + "/rootdesc.xml");
            HttpURLConnection conn = (HttpURLConnection) deviceUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                result.append("   ✅ 设备描述文档可访问\n");
            } else {
                result.append("   ❌ 设备描述文档访问失败，HTTP代码: ").append(responseCode).append("\n");
            }
        } catch (Exception e) {
            result.append("   ❌ 设备描述文档测试失败: ").append(e.getMessage()).append("\n");
        }

        return result.toString().replace("\n", "<br>");
    }

    /**
     * 测试组播通信
     */
    private void testMulticastCommunication(StringBuilder result) {
        try {
            // 创建测试socket
            DatagramSocket testSocket = new DatagramSocket();
            testSocket.setSoTimeout(3000);

            // 发送M-SEARCH请求
            String searchMessage = "M-SEARCH * HTTP/1.1\r\n" +
                    "HOST: 239.255.255.250:1900\r\n" +
                    "MAN: \"ssdp:discover\"\r\n" +
                    "MX: 3\r\n" +
                    "ST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n" +
                    "\r\n";

            byte[] sendData = searchMessage.getBytes("UTF-8");
            DatagramPacket sendPacket = new DatagramPacket(
                    sendData,
                    sendData.length,
                    InetAddress.getByName("239.255.255.250"),
                    1900
            );

            testSocket.send(sendPacket);
            result.append("   ✅ 已发送M-SEARCH请求\n");

            // 尝试接收响应
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                testSocket.receive(receivePacket);
                String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                result.append("   ✅ 收到SSDP响应:\n");
                result.append("      来源: ").append(receivePacket.getAddress().getHostAddress()).append("\n");
                result.append("      内容: ").append(response.split("\r\n")[0]).append("\n");
            } catch (SocketTimeoutException e) {
                result.append("   ⚠️  未收到SSDP响应（超时）\n");
                result.append("      可能原因:\n");
                result.append("      - 防火墙阻挡了组播\n");
                result.append("      - 网络设备隔离了组播流量\n");
                result.append("      - SSDP服务未正确响应\n");
            }

            testSocket.close();

        } catch (Exception e) {
            result.append("   ❌ 组播测试失败: ").append(e.getMessage()).append("\n");
        }
    }

    /**
     * 强制发送设备广播通知
     */
    @GetMapping("/force-broadcast")
    public String forceBroadcast() {
        try {
            ssdpService.sendAliveNotification();
            return "✅ 已强制发送设备广播通知";
        } catch (Exception e) {
            return "❌ 广播失败: " + e.getMessage();
        }
    }
}